<template>
  <view class="statistics-page">
    <view class="header">
      <text class="title">支付统计</text>
    </view>
    
    <!-- 统计卡片 -->
    <view class="stats-cards">
      <view class="stat-card">
        <view class="stat-icon success">
          <text class="iconfont icon-check"></text>
        </view>
        <view class="stat-content">
          <text class="stat-value">{{ statistics.totalPayments || 0 }}</text>
          <text class="stat-label">总支付次数</text>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="stat-icon amount">
          <text class="iconfont icon-money"></text>
        </view>
        <view class="stat-content">
          <text class="stat-value">¥{{ statistics.totalAmount || 0 }}</text>
          <text class="stat-label">总支付金额</text>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="stat-icon rate">
          <text class="iconfont icon-chart"></text>
        </view>
        <view class="stat-content">
          <text class="stat-value">{{ statistics.successRate || 0 }}%</text>
          <text class="stat-label">支付成功率</text>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="stat-icon refund">
          <text class="iconfont icon-refund"></text>
        </view>
        <view class="stat-content">
          <text class="stat-value">¥{{ statistics.totalRefundAmount || 0 }}</text>
          <text class="stat-label">总退款金额</text>
        </view>
      </view>
    </view>
    
    <!-- 时间筛选 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          class="tab-item" 
          :class="{ active: currentPeriod === period.value }"
          v-for="period in timePeriods" 
          :key="period.value"
          @click="selectPeriod(period.value)"
        >
          <text>{{ period.label }}</text>
        </view>
      </view>
    </view>
    
    <!-- 图表区域 -->
    <view class="chart-section">
      <view class="chart-title">支付趋势</view>
      <view class="chart-container">
        <canvas canvas-id="paymentChart" class="chart-canvas"></canvas>
      </view>
    </view>
    
    <!-- 支付方式统计 -->
    <view class="method-section">
      <view class="section-title">支付方式统计</view>
      <view class="method-list">
        <view class="method-item" v-for="method in paymentMethods" :key="method.method">
          <view class="method-info">
            <text class="method-name">{{ method.name }}</text>
            <text class="method-count">{{ method.count }}次</text>
          </view>
          <view class="method-bar">
            <view class="bar-bg">
              <view class="bar-fill" :style="{ width: method.percentage + '%' }"></view>
            </view>
            <text class="percentage">{{ method.percentage }}%</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 最近支付记录 -->
    <view class="recent-section">
      <view class="section-title">最近支付记录</view>
      <view class="recent-list">
        <view v-if="recentPayments.length === 0" class="empty">
          <text>暂无支付记录</text>
        </view>
        <view v-else class="recent-item" v-for="payment in recentPayments" :key="payment.paymentId">
          <view class="payment-info">
            <text class="order-no">{{ payment.orderNo }}</text>
            <text class="amount">¥{{ payment.paymentAmount }}</text>
          </view>
          <view class="payment-meta">
            <text class="method">{{ payment.paymentMethod === 'WXPAY' ? '微信支付' : payment.paymentMethod }}</text>
            <text class="time">{{ formatTime(payment.createTime) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { payService } from '@/services/pay.js'

export default {
  data() {
    return {
      statistics: {},
      currentPeriod: 'month',
      timePeriods: [
        { value: 'week', label: '本周' },
        { value: 'month', label: '本月' },
        { value: 'quarter', label: '本季度' },
        { value: 'year', label: '本年' }
      ],
      paymentMethods: [],
      recentPayments: []
    }
  },
  
  onLoad() {
    this.loadStatistics()
  },
  
  onPullDownRefresh() {
    this.loadStatistics()
  },
  
  methods: {
    async loadStatistics() {
      try {
        const params = {
          period: this.currentPeriod
        }
        
        const res = await payService.getPaymentStatistics(params)
        
        if (res.success) {
          this.statistics = res.data.statistics || {}
          this.paymentMethods = res.data.paymentMethods || []
          this.recentPayments = res.data.recentPayments || []
          
          // 绘制图表
          this.$nextTick(() => {
            this.drawChart(res.data.chartData || [])
          })
        } else {
          uni.showToast({
            title: res.message || '获取统计数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        uni.stopPullDownRefresh()
      }
    },
    
    selectPeriod(period) {
      this.currentPeriod = period
      this.loadStatistics()
    },
    
    drawChart(chartData) {
      // 这里可以集成图表库，如 uCharts 或 ECharts
      // 暂时使用简单的 canvas 绘制
      const ctx = uni.createCanvasContext('paymentChart')
      
      if (chartData.length === 0) {
        ctx.setFillStyle('#999')
        ctx.fillText('暂无数据', 150, 100)
        ctx.draw()
        return
      }
      
      const canvasWidth = 300
      const canvasHeight = 200
      const padding = 40
      const chartWidth = canvasWidth - padding * 2
      const chartHeight = canvasHeight - padding * 2
      
      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制坐标轴
      ctx.setStrokeStyle('#ddd')
      ctx.beginPath()
      ctx.moveTo(padding, padding)
      ctx.lineTo(padding, canvasHeight - padding)
      ctx.lineTo(canvasWidth - padding, canvasHeight - padding)
      ctx.stroke()
      
      // 绘制数据点
      const maxValue = Math.max(...chartData.map(item => item.value))
      const stepX = chartWidth / (chartData.length - 1)
      
      ctx.setStrokeStyle('#007aff')
      ctx.setLineWidth(2)
      ctx.beginPath()
      
      chartData.forEach((item, index) => {
        const x = padding + index * stepX
        const y = canvasHeight - padding - (item.value / maxValue) * chartHeight
        
        if (index === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
        
        // 绘制数据点
        ctx.setFillStyle('#007aff')
        ctx.beginPath()
        ctx.arc(x, y, 3, 0, 2 * Math.PI)
        ctx.fill()
      })
      
      ctx.stroke()
      ctx.draw()
    },
    
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .header {
    background-color: #fff;
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .stats-cards {
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx;
    
    .stat-card {
      width: calc(50% - 10rpx);
      background-color: #fff;
      border-radius: 12rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      display: flex;
      align-items: center;
      
      &:nth-child(odd) {
        margin-right: 20rpx;
      }
      
      .stat-icon {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
        
        .iconfont {
          font-size: 40rpx;
          color: #fff;
        }
        
        &.success {
          background-color: #52c41a;
        }
        
        &.amount {
          background-color: #ff4d4f;
        }
        
        &.rate {
          background-color: #1890ff;
        }
        
        &.refund {
          background-color: #fa8c16;
        }
      }
      
      .stat-content {
        flex: 1;
        
        .stat-value {
          display: block;
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .stat-label {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
  
  .filter-section {
    background-color: #fff;
    margin-bottom: 20rpx;
    
    .filter-tabs {
      display: flex;
      padding: 20rpx;
      
      .tab-item {
        flex: 1;
        text-align: center;
        padding: 15rpx 0;
        font-size: 28rpx;
        color: #666;
        border-radius: 25rpx;
        margin: 0 10rpx;
        
        &.active {
          background-color: #007aff;
          color: #fff;
        }
      }
    }
  }
  
  .chart-section {
    background-color: #fff;
    margin-bottom: 20rpx;
    padding: 30rpx;
    
    .chart-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 30rpx;
    }
    
    .chart-container {
      .chart-canvas {
        width: 100%;
        height: 400rpx;
      }
    }
  }
  
  .method-section {
    background-color: #fff;
    margin-bottom: 20rpx;
    padding: 30rpx;
    
    .section-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 30rpx;
    }
    
    .method-list {
      .method-item {
        margin-bottom: 30rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .method-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15rpx;
          
          .method-name {
            font-size: 28rpx;
            color: #333;
          }
          
          .method-count {
            font-size: 26rpx;
            color: #666;
          }
        }
        
        .method-bar {
          display: flex;
          align-items: center;
          
          .bar-bg {
            flex: 1;
            height: 20rpx;
            background-color: #f0f0f0;
            border-radius: 10rpx;
            margin-right: 20rpx;
            overflow: hidden;
            
            .bar-fill {
              height: 100%;
              background-color: #007aff;
              border-radius: 10rpx;
              transition: width 0.3s ease;
            }
          }
          
          .percentage {
            font-size: 24rpx;
            color: #666;
            min-width: 60rpx;
          }
        }
      }
    }
  }
  
  .recent-section {
    background-color: #fff;
    padding: 30rpx;
    
    .section-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 30rpx;
    }
    
    .recent-list {
      .empty {
        text-align: center;
        padding: 60rpx 0;
        color: #999;
        font-size: 28rpx;
      }
      
      .recent-item {
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .payment-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10rpx;
          
          .order-no {
            font-size: 28rpx;
            color: #333;
          }
          
          .amount {
            font-size: 28rpx;
            color: #ff4d4f;
            font-weight: bold;
          }
        }
        
        .payment-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .method {
            font-size: 24rpx;
            color: #666;
          }
          
          .time {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
  }
}
</style> 